﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;

namespace App_Code.Helpers
{
    /// <summary>
    /// Summary description for VideozerExtractor
    /// </summary>
    public class VideozerExtractor
    {
        private const string CONTROL_URI = "http://www.videozer.com/player_control/settings.php?v={0}";
        private const string URL_REGEX = @"http://www.videozer.com/embed/([A-Za-z0-9]+)";
        private const string MOVIE_URL = "http://www.videozer.com/embed/";
        private const string TOKEN = "\"token1\":\"(.+?)\"";

        public static List<string> GetMovieUrls(string content)
        {
            var movieUrls = new List<string>();
            var exp = new Regex(URL_REGEX, RegexOptions.IgnoreCase);
            var matches = exp.Matches(content);
            foreach (Match match in matches)
            {
                if (match.Success)
                {
                    var movieUrl = match.Value;
                    if (!movieUrls.Contains(movieUrl))
                    {
                        movieUrls.Add(movieUrl);
                    }
                }
            }
            return movieUrls;
        }

        public static VideoResult ExtractMovieUrl(string movieUrl)
        {
            var movieCode = movieUrl.Replace(MOVIE_URL, string.Empty);
            var content = Utils.GetPage(string.Format(CONTROL_URI, movieCode), Encoding.Default);

            if (content.Contains("This video was either deleted by the user or in breach of a copyright holder"))
            {
                throw new Exception("This video was either deleted by the user or in breach of a copyright holder");
            }

            var match = Regex.Match(content, TOKEN, RegexOptions.IgnoreCase);
            if (!match.Success)
            {
                throw new Exception("Cant find videozer token");
            }

            var convertedBytes = Convert.FromBase64String(match.Groups[1].Value.Replace("\\", string.Empty));

            const string videoTitleRegEx = "\"video\":{\"title\":\"(.+?)\"";
            match = Regex.Match(content, videoTitleRegEx, RegexOptions.IgnoreCase);
            return match.Success ?
                new VideoResult(Encoding.UTF8.GetString(convertedBytes), match.Groups[1].Value, true) :
                new VideoResult(Encoding.UTF8.GetString(convertedBytes), true);
        }

        public static bool IsContainVideoLink(string content)
        {
            var match = Regex.Match(content, URL_REGEX, RegexOptions.IgnoreCase);
            return match.Success;
        }
    }
}